#[derive(Debug)]
enum FileState {
    Open,
    Closed,
}
#[derive(Debug)]
struct File {
    name: String,
    data: Vec<u8>,
    state: FileState,
}
impl File {
    // 定义new函数
    fn new(name: &str) -> File {
        File {
            name: String::from(name),
            data: Vec::new(),
            state: FileState::Closed,
        }
    }
    #[allow(dead_code)]
    // 预存入数据
    fn new_with_data(name: &str, data: &Vec<u8>) -> File {
        let mut f = File::new(name);
        f.data = data.clone();
        f
    }
    // 使用self替代f
    fn read(self: &File, save_to: &mut Vec<u8>) -> Result<usize, String> {
        //使用Result<T,E>
        let mut tmp = self.data.clone();
        let read_length = tmp.len();

        save_to.reserve(read_length); //分配内存
        save_to.append(&mut tmp);
        Ok(read_length)
    }
}
fn open(mut f: File) -> Result<File, String> {
    f.state = FileState::Open;
    Ok(f)
}
fn close(mut f: File) -> Result<File, String> {
    f.state = FileState::Closed;
    Ok(f)
}
#[allow(dead_code)]
fn read(f: &File, save_to: &mut Vec<u8>) -> usize {
    //不返回数据
    let mut tmp = f.data.clone();
    let read_length = tmp.len();

    save_to.reserve(read_length); //分配内存
    save_to.append(&mut tmp);
    read_length
}

fn main() {
    let mut f5 = File::new("5.txt");
    let mut buffer: Vec<u8> = vec![];

    if f5.read(&mut buffer).is_err() {
        println!("Error checking is working");
    }
    //与文件交互 从Ok中解包
    f5 = open(f5).unwrap();
    let f5_length = f5.read(&mut buffer).unwrap();
    f5 = close(f5).unwrap();

    let _text = String::from_utf8_lossy(&buffer); // 将Vec<u8>转为String,无效的字符会被换成乱码

    println!("{:?}", f5);
    println!("{} is {} bytes long", &f5.name, f5_length);
}
